<template>
  <div class="container">
    <div class="top">
      <span>金额：</span>
      <el-input
        style="width: 200px"
        v-model="price"
        :disabled="true"
      ></el-input>
      <el-input
        style="width: 300px"
        :disabled="true"
        placeholder="请搜索供应商信息"
        v-model="supplierNameList.name"
      >
        <template slot="prepend"
          >供应商</template
        >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="supplierBtn"
        ></el-button>
      </el-input>
      <el-input
        style="width: 300px"
        class="inp"
        :disabled="true"
        placeholder="请搜索类别信息"
        v-model="classNameList.name"
      >
        <template slot="prepend"
          >类别</template
        >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="classBtn"
        ></el-button>
      </el-input>
      <el-select
        v-model="search.area"
        filterable
        remote
        center
        reserve-keyword
        placeholder="请输入区域"
        :remote-method="insideRemoteMethods"
        :loading="insideArea.loading"
        @change="area"
      >
        <el-option
          v-for="item in insideArea.options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-checkbox
        v-model="search.amount"
        label="不包含应结金额为0数据"
        border
      ></el-checkbox>
      <el-input
        style="width: 200px"
        v-model="search.bank"
        placeholder="请输入开户行"
      ></el-input>
      <el-input
        style="width: 200px"
        v-model="search.serial_code"
        placeholder="请输入付款单号"
      ></el-input>

      <el-input
        style="width: 200px"
        v-model="search.bank_acount"
        placeholder="请输入银行卡号"
      ></el-input>
      <el-select
        v-model="search.status"
        @change="status"
        placeholder="付款状态"
      >
        <el-option
          v-for="item in option"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>

      <el-select
        v-model="search.pay_status"
        @change="status"
        placeholder="支付完成状态"
      >
        <el-option
          v-for="item in payoption"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
      <div style="display: inline-block">
        制单时间：
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="dates"
          type="daterange"
          :clearable="false"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </div>
      <div style="display: inline-block">
        到账期时间：
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="date"
          type="daterange"
          :clearable="false"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </div>
      <div style="display: inline-block">
        付款时间：
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="dateTime"
          type="daterange"
          :clearable="false"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
        <el-select v-model="search.must_pay" placeholder="必付状态">
          <el-option
            v-for="item in must_payList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div style="display: inline-block">
        挑单时间：
        <el-date-picker
          value-format="yyyy-MM-dd"
          v-model="tdDate"
          type="daterange"
          :clearable="false"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </div>
      <el-button
        size="small"
        type="primary"
        icon="el-icon-search"
        class="handleSearch"
        @click="handleSearch()"
        >查询
      </el-button>
      <el-button
        size="small"
        type="danger"
        class="handleSearch"
        icon="el-icon-delete"
        @click="empty()"
        >清空</el-button
      >
      <el-button
        size="small"
        type="success"
        class="handleSearch"
        icon="el-icon-edit"
        @click="auditCenter()"
        >付款
      </el-button>
      <el-button
        size="small"
        type="primary"
        class="handleSearch"
        icon="el-icon-bank-card"
        @click="moresendPay()"
        >线上付款
      </el-button>
      <el-button
        size="small"
        type="warning"
        class="handleSearch"
        icon="el-icon-edit"
        @click="cancels()"
        >取消付款单
      </el-button>
      <el-button
        size="small"
        type="primary"
        class="handleSearch"
        icon="el-icon-warning-outline"
        @click="sduitpayallinfo()"
        >修改付款账户</el-button
      >
      <el-button
        type="info"
        size="small"
        icon="el-icon-tickets"
        @click="derive()"
        >导出</el-button
      >
    </div>
    <el-table
      max-height="600"
      :data="tableData"
      ref="multipleTable"
      tooltip-effect="dark"
      border
      style="width: 100%"
      empty-text="暂无数据"
      @selection-change="handleSelectionChange"
      class="hidden-xs-only"
      show-summary
      :summary-method="getSummaries"
    >
      <el-table-column
        type="selection"
        :selectable="selectable"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="xuhao"
        label="序号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="supplier_name"
        label="供应商"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="serial_code"
        label="付款单号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="bank"
        label="开户行"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="bank_account"
        label="银行卡号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="bank_name"
        label="付款账户"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="account"
        label="付款账户卡号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="payment_days"
        label="账期时间(天)"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="pay_date"
        label="到账期时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="check_date"
        label="挑单时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="last_pay_time"
        label="付款时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="amount"
        label="应结金额"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="pay_amount"
        label="已结金额"
        align="center"
      ></el-table-column>
      <el-table-column label="本期结算金额" align="center" width="180">
        <template slot-scope="scope">
          <el-input-number
            @blur="settle(scope)"
            :controls="false"
            v-model="scope.row.settle"
            size="mini"
            controls-position="right"
            :disabled="scope.row.status == 2 || scope.row.settle < 0"
            :precision="2"
            :step="1"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        prop="statusMsg"
        label="状态"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="created_at"
        label="创建时间"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="complete"
        label="支付完成状态"
        align="center"
      ></el-table-column>
      <el-table-column label="支付详情" align="center" width="300px">
        <template slot-scope="scope">
          <div v-for="item in scope.row.details" :key="item">
            <div>{{ item }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="class_name"
        label="一级分类"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="360px">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-s-tools"
            @click="modification(scope)"
            v-if="scope.row.status != 2"
            >结算金额设置</el-button
          >
          <el-button
            size="small"
            type="success"
            class="handleSearch"
            icon="el-icon-edit"
            @click="audit(scope)"
            v-if="scope.row.status != 2"
            >付款</el-button
          >
          <el-button
            size="small"
            type="primary"
            class="handleSearch"
            icon="el-icon-edit"
            @click="onesendPay(scope)"
            v-if="scope.row.status != 2"
            >线上付款</el-button
          >

          <el-button
            size="small"
            type="warning"
            class="handleSearch"
            icon="el-icon-edit"
            @click="cancel(scope)"
            v-if="scope.row.status == 1"
            >取消付款单</el-button
          >
          <el-button
            size="small"
            type="info"
            class="handleSearch"
            icon="el-icon-warning-outline"
            @click="sendinfo(scope)"
            >付款详情</el-button
          >
          <el-button
            size="small"
            type="warning"
            class="handleSearch"
            icon="el-icon-warning-outline"
            @click="sduitpayinfo(scope)"
            v-if="scope.row.type == 1"
            >修改付款账户</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="结算金额设置"
      :visible.sync="dialog.centerDialogVisible"
      center
      @open="getDatas"
      width="800px"
    >
      <el-table
        max-height="600"
        :data="tableDatas"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <!-- <el-table-column prop="xuhao" label="序号" align="center"></el-table-column> -->
        <el-table-column
          prop="serial_code"
          label="结算单号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="amount"
          label="应结金额"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="pay_amount"
          label="已结金额"
          align="center"
        ></el-table-column>
        <el-table-column label="本期结算金额" align="center" width="180">
          <template slot-scope="scope">
            <el-input-number
              :controls="false"
              v-model="scope.row.unliquidated"
              size="mini"
              controls-position="right"
              :disabled="scope.row.status == 2 || scope.row.type == 10"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="typeMsg"
          label="类型"
          align="center"
        ></el-table-column>
        <!-- <el-table-column prop="cw_statusMsg" label="状态" align="center"></el-table-column> -->
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <pagination
      @page="handleSizeChange"
      @pagesize="handleCurrentChange"
      :pageData="pageData"
    ></pagination>
    <div style="height: 0">
      <supplierSearch
        :supplierdialog="supplierdialog"
        @tag="supplierTag"
      ></supplierSearch>
      <sendPayDialog
        :sendPayDialog="sendPayDialog"
        @upData="getupData"
      ></sendPayDialog>
      <sendPayinfoDialog
        :sendPayinfoDialog="sendPayinfoDialog"
        @upData="getupData"
      ></sendPayinfoDialog>
      <classDialog :classdialog="classdialog" @tag="classTag"></classDialog>
      <eduitestablishDialog
        :eduitestablishDialog="eduitestablishDialog"
        @upData="getupData"
      ></eduitestablishDialog>
    </div>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { getnowDate } from "@/utils/index";
import SupplierSearch from "@/components/superGrossMargin/supplierSearch";
import { supplierList, getRegionData } from "@/api/supplier/supplierList";
import Pagination from "@/components/pagination";
import ClassDialog from "@/components/superSettlement/classDialog";
import SendPayDialog from "@/components/settlement/sendPayDialog";
import EduitestablishDialog from "@/components/settlement/eduitestablishDialog";
import SendPayinfoDialog from "@/components/settlement/sendPayinfoDialog";
import {
  caiwuStatementList,
  findCaiwuStatementInfo,
  confirmStatement,
  cancelPayBill
} from "@/api/superSettlement/settlementList";
export default {
  components: {
    pagination: Pagination,
    supplierSearch: SupplierSearch,
    sendPayDialog: SendPayDialog,
    sendPayinfoDialog: SendPayinfoDialog,
    eduitestablishDialog: EduitestablishDialog,
    classDialog: ClassDialog
  },
  data() {
    return {
      //页面数据
      tableData: [],
      tableDatas: [],
      //分页
      pageData: {
        pageSizes: [10, 20],
        pageSize: 10,
        page: 1,
        total: null,
        layout: "total, sizes, prev, pager, next, jumper"
      },
      date: [],
      dates: [],
      dateTime: [],
      tdDate: [],
      //dialog信息
      dialog: {
        centerDialogVisible: false,
        id: "",
        amount: "",
        index: 0,
        supplier_id: ""
      },
      sendPayDialog: {
        dialogPrince: "",
        dialogJsonstr: "",
        dialogType: "",
        dialogVisible: false
      },
      sendPayinfoDialog: {
        id: "",
        dialogType: "",
        dialogVisible: false
      },
      eduitestablishDialog: {
        id: "",
        paymentname: "",
        dialogType: "",
        eduitDialogVisible: false
      },
      classNameList: {
        name: "",
        code: ""
      },
      //默认时间
      // normal_startime: getnowDate().startimer,
      // normal_endtime: getnowDate().endtimer,
      search: {
        start_time: "",
        end_time: "",
        create_start: "",
        create_end: "",
        pay_start_date: "",
        pay_end_date: "",
        bank: "",
        bank_acount: "",
        status: "",
        serial_code: "",
        area: "",
        amount: true,
        pay_status: "",
        must_pay: "",
        td_start_date: "",
        td_end_date: ""
      },
      insideArea: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      },
      price: 0,
      listData: [],
      bool: false,
      handleSelection: [],
      listCenter: {},
      classdialog: {
        centerDialogVisible: false
      },
      //dialog信息
      supplierdialog: {
        centerDialogVisible: false
      },

      supplierNameList: {
        name: "",
        id: "",
        code: ""
      },
      option: [
        {
          value: 0,
          label: "全部"
        },
        {
          value: 1,
          label: "待付款"
        },
        {
          value: 2,
          label: "已付款"
        },
        {
          value: 3,
          label: "不结算"
        }
      ],
      payoption: [
        {
          value: -1,
          label: "全部"
        },
        {
          value: 0,
          label: "未完成"
        },
        {
          value: 1,
          label: "已完成"
        }
      ],
      selectedData: [],
      center: {},
      must_payList: [
        {
          value: -1,
          label: "全部"
        },
        {
          value: 0,
          label: "非必付供应商"
        },
        {
          value: 1,
          label: "必付供应商"
        }
      ]
    };
  },

  created() {
    // this.search.start_time = this.normal_startime;
    // this.search.end_time = this.normal_endtime;
    // this.search.create_start = this.normal_startime;
    // this.search.create_end = this.normal_endtime;
    // if (this.normal_startime) {
    //   this.date.push(this.search.start_time);
    //   this.dates.push(this.search.create_start);
    // }
    // if (this.normal_endtime) {
    //   this.date.push(this.search.end_time);
    //   this.dates.push(this.search.create_end);
    // }
    this.getData();
    this.getAreaData();
  },
  methods: {
    //获取页面数据
    getData() {
      let data = {
        limit: this.pageData.pageSize,
        page: this.pageData.page,
        bank: this.search.bank,
        bank_account: this.search.bank_acount,
        start_date: this.search.start_time,
        end_date: this.search.end_time,
        pay_start_date: this.search.pay_start_date,
        pay_end_date: this.search.pay_end_date,
        create_start: this.search.create_start,
        create_end: this.search.create_end,
        serial_code: this.search.serial_code,
        status: this.search.status == 0 ? "" : this.search.status,
        complete: this.search.pay_status == -1 ? "" : this.search.pay_status,
        must_pay: this.search.must_pay == -1 ? "" : this.search.must_pay,
        orgarea_code_str: this.search.area,
        amount: this.search.amount ? 1 : "",
        category_code: this.classNameList.code,
        td_start_date: this.search.td_start_date,
        td_end_date: this.search.td_end_date
      };
      if (this.supplierNameList.code) {
        data.supplier_id = this.supplierNameList.code;
        data.sup_id = this.supplierNameList.id;
      }
      caiwuStatementList(data)
        .then(res => {
          if (res.code == 0) {
            res.data.data.forEach(res => {
              res.settle = res.unliquidated;
              switch (res.status) {
                case 1:
                  res.statusMsg = "待付款";
                  break;
                case 2:
                  res.statusMsg = "已付款";
                  break;
                case 3:
                  res.statusMsg = "部分付款";
                  break;
              }
              res.relevance =
                res.type == 0 ? res.storage_bill_id : res.return_id;
              switch (res.cw_status) {
                case 0:
                  res.cw_statusMsg = "正常";
                  break;
                case 1:
                  res.cw_statusMsg = "冻结";
                  break;
                case 2:
                  res.cw_statusMsg = "不结算 ";
                  break;
              }
              let unliquidated = {
                row: {
                  settle: res.unliquidated,
                  id: res.id,
                  pay_amount: res.pay_amount
                }
              };
              this.settle(unliquidated);
            });
            this.tableData = res.data.data;
            this.pageData.page = res.data.current_page;
            this.pageData.pagesize = res.data.per_page;
            this.pageData.total = res.data.total;
            this.lists = res.data.data.filter(res => {
              return res.type == 10;
            });
          }
        })
        .then(() => {
          this.lists.forEach((res, index) => {
            this.$refs.multipleTable.toggleRowSelection(
              this.lists[index],
              true
            );
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    getAreaData() {
      let data = {
        page: 1,
        limit: 50
      };

      //获取初始化区域列表
      getRegionData(data).then(res => {
        this.insideArea.options = res.data.paginate.map(item => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
      });
    },
    // 搜索区域
    insideRemoteMethods(query) {
      if (query !== "") {
        this.getSupplierLists(query);
      } else {
        this.insideArea.options = [];
      }
    },
    getSupplierLists(query) {
      let data = {
        name: query,
        page: 1,
        limit: 100
      };
      getRegionData(data).then(res => {
        this.insideArea.options = res.data.paginate.map(item => {
          return { value: `${item.code}`, label: `${item.name}` };
        });
      });
    },
    //超级类别搜索
    classBtn() {
      this.classdialog = {
        centerDialogVisible: true
      };
    },
    classTag(data) {
      this.classNameList = {
        name: "",
        code: ""
      };
      console.log(data, 11111);
      let arrName = [];
      let arrCode = [];
      data.forEach(res => {
        arrName.push(res.name);
        arrCode.push(res.code);
      });
      this.classNameList.name = arrName.join(",");
      this.classNameList.code = arrCode.join(",");
    },
    //取消付款单
    cancel(scope) {
      this.$confirm("是否取消该付款单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            id: scope.row.id
          };
          cancelPayBill(data).then(res => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.message || res.msg
              });
              this.listData = [];
              this.getData();
            } else {
              this.$message({
                type: "info",
                message: res.message || res.msg
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    getDatas() {
      if (this.listData.length != 0) {
        this.bool = false;
        let supplier = this.dialog.supplier_id;
        let center = [];
        this.listData.forEach(res => {
          if (res[supplier]) {
            this.bool = true;
            center = res[supplier];
          }
        });
        if (this.bool) {
          let data = {
            id: this.dialog.id,
            amount: this.dialog.inp
          };
          findCaiwuStatementInfo(data).then(result => {
            if (result.code == 0) {
              result.data.forEach(res => {
                res.settle = 0.0;
                // res.typeMsg = res.type == 10 ? "入库单结算单" : "返货单结算单";
                switch (res.kind) {
                  case 10:
                    res.typeMsg = "入库单结算单";
                    break;
                  case 30:
                    res.typeMsg = "高退低进结算单";
                    break;
                  case 50:
                    res.typeMsg = "返点结算单";
                    break;
                  case 51:
                    res.typeMsg = "返利返点负结算单";
                    break;
                  case 52:
                    res.typeMsg = "物流返点负结算单";
                    break;
                  case 60:
                    res.typeMsg = "返货生成负结算单";
                    break;
                  case 61:
                    res.typeMsg = "返利返点正结算单";
                    break;
                  case 62:
                    res.typeMsg = "物流返点正结算单";
                    break;
                  case 91:
                    res.typeMsg = "费用单结算单";
                    break;
                  default:
                    res.typeMsg = "未知类型结算单";
                }
                switch (res.cw_status) {
                  case 0:
                    res.cw_statusMsg = "正常";
                    break;
                  case 1:
                    res.cw_statusMsg = "冻结";
                    break;
                  case 2:
                    res.cw_statusMsg = "不结算 ";
                    break;
                }
                if (center.list.length != 0) {
                  if (res.unliquidated > 0) {
                    res.unliquidated = 0;
                  }

                  center.list.forEach(item => {
                    if (item.sid == res.id) {
                      res.unliquidated = item.amount;
                    }
                  });
                }
              });
              this.tableDatas = result.data;
            }
          });
        } else {
          this.bool = false;
          this.getTabData();
        }
      } else {
        this.bool = false;
        this.getTabData();
      }
    },
    getTabData() {
      let data = {
        id: this.dialog.id,
        amount: this.dialog.inp
      };
      findCaiwuStatementInfo(data).then(result => {
        if (result.code == 0) {
          result.data.forEach(res => {
            res.settle = 0.0;
            res.typeMsg = res.type != 10 ? "入库单结算单" : "返货单结算单";
            switch (res.cw_status) {
              case 0:
                res.cw_statusMsg = "正常";
                break;
              case 1:
                res.cw_statusMsg = "冻结";
                break;
              case 2:
                res.cw_statusMsg = "不结算 ";
                break;
            }
          });
          this.tableDatas = result.data;
        }
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (index != 12) {
            sums[index] = "";
          } else {
            sums[index] = sums[index].toFixed(4);
          }
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },

    //超级供应商搜索
    supplierBtn() {
      this.supplierdialog = {
        centerDialogVisible: true
      };
    },
    supplierTag(data) {
      this.supplierNameList = {
        name: "",
        id: "",
        code: ""
      };
      let arrName = [];
      let arrId = [];
      let arrCode = [];
      let arr = [];
      data.forEach(res => {
        arrName.push(res.name);
        arrId.push(res.id);
        arrCode.push(res.code);
        arr.push(res.name);
      });
      this.supplierNameList.name = arrName.join(",");
      this.supplierNameList.id = arrId.join(",");
      this.supplierNameList.code = arrCode.join(",");

      this.center["供应商"] = arr;
    },
    // 结算设置
    modification(scope) {
      this.listCenter = {};
      this.$refs.multipleTable.clearSelection();
      this.dialog.centerDialogVisible = true;
      this.dialog.id = scope.row.id;
      this.dialog.inp = scope.row.settle;
      this.dialog.index = scope.$index;
      this.dialog.supplier_id = scope.row.id;
      this.dialog.pay_amount = scope.row.pay_amount;
    },

    // 结算关闭
    confirm() {
      if (this.bool) {
        let supplier = this.dialog.supplier_id;
        let sum = 0;
        this.listData.forEach((res, index) => {
          if (res[supplier]) {
            res[supplier].id = this.dialog.id;
            res[supplier].list = [];
            res[supplier].amount = 0;
            res.pay_amount = this.dialog.pay_amount;
            this.tableDatas.forEach((result, index) => {
              res[supplier].amount += result.unliquidated;
              if (result.unliquidated) {
                res[supplier].list.push({
                  sid: result.id,
                  amount: result.unliquidated
                });
              }
              sum += result.unliquidated;
            });
          }
        });
        this.tableData[this.dialog.index].settle = sum;
        this.dialog.centerDialogVisible = false;
      } else {
        let list = [];
        let sum = 0;

        let supplier = this.dialog.supplier_id;
        this.tableDatas.forEach(res => {
          sum += res.unliquidated;
          if (res.unliquidated != 0) {
            list.push({
              sid: res.id,
              amount: res.unliquidated
            });
          }
        });
        this.listData.push({
          [supplier]: {
            id: this.dialog.id,
            pay_amount: this.dialog.pay_amount,
            amount: sum,
            list: list
          }
        });
        this.tableData[this.dialog.index].settle = sum;
        this.dialog.centerDialogVisible = false;
      }
    },
    //修改本期结算金额
    settle(scope) {
      this.listCenter = {};
      this.$refs.multipleTable.clearSelection();
      if (scope.row.settle) {
        let supplier = scope.row.id;
        let index = 0;
        let bool = false;
        this.listData.forEach((res, indexs) => {
          if (res[supplier]) {
            index = indexs;
            bool = true;
          }
        });
        if (bool) {
          this.listData.splice(index, 1);
        }
        this.listData.push({
          [supplier]: {
            id: scope.row.id,
            pay_amount: scope.row.pay_amount,
            amount: scope.row.settle,
            list: []
          }
        });
      } else if (scope.row.settle == 0) {
        let supplier = scope.row.id;
        let index = 0;
        let bool = false;
        this.listData.forEach((res, indexs) => {
          if (res[supplier]) {
            index = indexs;
            bool = true;
          }
        });
        if (bool) {
          this.listData.splice(index, 1);
        }
        this.listData.push({
          [supplier]: {
            id: scope.row.id,
            pay_amount: scope.row.pay_amount,
            amount: scope.row.settle,
            list: []
          }
        });
      } else {
        scope.row.settle = "0.00";
        let supplier = scope.row.id;
        let index = 0;
        let bool = false;
        this.listData.forEach((res, indexs) => {
          if (res[supplier]) {
            index = indexs;
            bool = true;
          }
        });
        this.listData.splice(index, 1);
      }
    },
    //付款（勾选）
    auditCenter() {
      if (this.handleSelection.length == 0) {
        this.$message({
          type: "info",
          message: "请选择供应商结算单"
        });
      } else {
        let amountNoticeArr = [];
        this.handleSelection.forEach(res => {
          if (res.pay_amount_notice) {
            amountNoticeArr.push(res.pay_amount_notice);
          }
        });
        // amountNoticeArr = [
        //   "错误提示一！！错误提示一！！！错误提示一！！！错误提示一！！！！",
        //   "错误提示一！！！",
        //   "错误提示二！！！",
        //   "错误提示三！！！"
        // ];
        if (amountNoticeArr.length > 0) {
          //2.新建newDatas数组
          let newDatas = [];
          const h = this.$createElement;
          //3.通过循环data数组，调用h方法，将每项值传给h,h('标签名',样式,具体内容)
          for (let i in amountNoticeArr) {
            //4.将data数据push进newDatas数组中
            newDatas.push(h("p", null, amountNoticeArr[i]));
          }
          this.$msgbox({
            title: "提示",
            message: h("div", null, newDatas),
            customClass: "test",
            showCancelButton: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消"
          })
            .then(() => {
              this.auditCenterFn();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        } else {
          this.auditCenterFn();
        }
      }
    },
    auditCenterFn() {
      let price = 0;
      for (var i in this.listCenter) {
        price += parseFloat(this.listCenter[i].amount);
      }
      price = price.toFixed(4);
      this.$confirm(`应付金额：${price},是否付款？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            jsonstr: JSON.stringify(this.listCenter)
          };
          confirmStatement(data).then(res => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.message || res.msg
              });
              this.listData = [];
              this.getData();
            } else {
              this.$message({
                type: "info",
                message: res.message || res.msg
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //付款
    audit(scope) {
      if (scope.row.pay_amount_notice) {
        this.$confirm(scope.row.pay_amount_notice, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let supplier = scope.row.id;
            let list = this.listData.filter(res => {
              return res[supplier];
            });
            let price = parseFloat(list[0][supplier].amount);
            price = price.toFixed(4);

            this.$confirm(`应付金额：${price},是否付款？`, {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                let supplier = scope.row.id;
                let index = 0;
                let center = null;
                this.listData.forEach((res, index) => {
                  if (res[supplier]) {
                    index = index;
                    center = res[supplier];
                  }
                });
                if (!center) {
                  this.$message({
                    type: "info",
                    message: "请设置结算金额"
                  });
                } else {
                  let main = { [supplier]: center };
                  let data = {
                    jsonstr: JSON.stringify(main)
                  };
                  confirmStatement(data).then(res => {
                    if (res.code == 0) {
                      this.$message({
                        type: "success",
                        message: res.message || res.msg
                      });
                      this.listData = [];
                      this.getData();
                    } else {
                      this.$message({
                        type: "info",
                        message: res.message || res.msg
                      });
                    }
                  });
                }
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消"
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      } else {
        let supplier = scope.row.id;
        let list = this.listData.filter(res => {
          return res[supplier];
        });
        let price = parseFloat(list[0][supplier].amount);
        price = price.toFixed(4);

        this.$confirm(`应付金额：${price},是否付款？`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let supplier = scope.row.id;
            let index = 0;
            let center = null;
            this.listData.forEach((res, index) => {
              if (res[supplier]) {
                index = index;
                center = res[supplier];
              }
            });
            if (!center) {
              this.$message({
                type: "info",
                message: "请设置结算金额"
              });
            } else {
              let main = { [supplier]: center };
              let data = {
                jsonstr: JSON.stringify(main)
              };
              confirmStatement(data).then(res => {
                if (res.code == 0) {
                  this.$message({
                    type: "success",
                    message: res.message || res.msg
                  });
                  this.listData = [];
                  this.getData();
                } else {
                  this.$message({
                    type: "info",
                    message: res.message || res.msg
                  });
                }
              });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      }
    },
    //勾选取消付款单
    cancels(scope) {
      this.$confirm("是否取消该付款单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            id: this.selectedData.join(",")
          };
          cancelPayBill(data).then(res => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.message || res.msg
              });
              this.listData = [];
              this.selectedData = [];
              this.getData();
            } else {
              this.$message({
                type: "info",
                message: res.message || res.msg
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //线上付款（勾选）
    moresendPay() {
      if (this.handleSelection.length == 0) {
        this.$message({
          type: "info",
          message: "请选择供应商结算单"
        });
      } else {
        let amountNoticeArr = [];
        this.handleSelection.forEach(res => {
          if (res.pay_amount_notice) {
            amountNoticeArr.push(res.pay_amount_notice);
          }
        });
        // amountNoticeArr = [
        //   "错误提示一！！错误提示一！！！错误提示一！！！错误提示一！！！！",
        //   "错误提示一！！！",
        //   "错误提示二！！！",
        //   "错误提示三！！！"
        // ];
        if (amountNoticeArr.length > 0) {
          //2.新建newDatas数组
          let newDatas = [];
          const h = this.$createElement;
          //3.通过循环data数组，调用h方法，将每项值传给h,h('标签名',样式,具体内容)
          for (let i in amountNoticeArr) {
            //4.将data数据push进newDatas数组中
            newDatas.push(h("p", null, amountNoticeArr[i]));
          }
          this.$msgbox({
            title: "提示",
            message: h("div", null, newDatas),
            customClass: "test",
            showCancelButton: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消"
          })
            .then(() => {
              this.moresendPayFn();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        } else {
          this.moresendPayFn();
        }
      }
    },
    moresendPayFn() {
      let price = 0;
      for (var i in this.listCenter) {
        price += parseFloat(this.listCenter[i].amount);
      }
      price = price.toFixed(4);
      this.$confirm(`应付金额：${price},是否线上付款？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.sendPayDialog.dialogPrince = price;
          this.sendPayDialog.dialogJsonstr = JSON.stringify(this.listCenter);
          this.sendPayDialog.dialogType = "smksend";
          this.sendPayDialog.dialogVisible = true;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //线上付款
    onesendPay(scope) {
      if (scope.row.pay_amount_notice) {
        this.$confirm(scope.row.pay_amount_notice, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let supplier = scope.row.id;
            let list = this.listData.filter(res => {
              return res[supplier];
            });
            let price = parseFloat(list[0][supplier].amount);
            price = price.toFixed(4);

            this.$confirm(`应付金额：${price},是否线上付款？`, {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
              .then(() => {
                let supplier = scope.row.id;
                let index = 0;
                let center = null;
                this.listData.forEach((res, index) => {
                  if (res[supplier]) {
                    index = index;
                    center = res[supplier];
                  }
                });
                if (!center) {
                  this.$message({
                    type: "info",
                    message: "请设置结算金额"
                  });
                } else {
                  let main = { [supplier]: center };
                  this.sendPayDialog.dialogJsonstr = JSON.stringify(main);
                  this.sendPayDialog.dialogPrince = price;
                  this.sendPayDialog.dialogType = "smksend";
                  this.sendPayDialog.dialogVisible = true;
                }
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消"
                });
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      } else {
        let supplier = scope.row.id;
        let list = this.listData.filter(res => {
          return res[supplier];
        });
        let price = parseFloat(list[0][supplier].amount);
        price = price.toFixed(4);

        this.$confirm(`应付金额：${price},是否线上付款？`, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            let supplier = scope.row.id;
            let index = 0;
            let center = null;
            this.listData.forEach((res, index) => {
              if (res[supplier]) {
                index = index;
                center = res[supplier];
              }
            });
            if (!center) {
              this.$message({
                type: "info",
                message: "请设置结算金额"
              });
            } else {
              let main = { [supplier]: center };
              this.sendPayDialog.dialogJsonstr = JSON.stringify(main);
              this.sendPayDialog.dialogPrince = price;
              this.sendPayDialog.dialogType = "smksend";
              this.sendPayDialog.dialogVisible = true;
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      }
    },
    getupData() {
      this.listData = [];
      this.$refs.multipleTable.clearSelection();
      this.getData();
    },
    //勾选取消付款单
    cancels(scope) {
      this.$confirm("是否取消该付款单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            id: this.selectedData.join(",")
          };

          cancelPayBill(data).then(res => {
            if (res.code == 0) {
              this.$message({
                type: "success",
                message: res.message || res.msg
              });
              this.listData = [];
              this.selectedData = [];
              this.getData();
            } else {
              this.$message({
                type: "info",
                message: res.message || res.msg
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    //付款详情
    sendinfo(scope) {
      console.log(scope, 33333);
      this.sendPayinfoDialog.id = scope.row.id;
      this.sendPayinfoDialog.dialogType = "smksend";
      this.sendPayinfoDialog.dialogVisible = true;
    },
    derive() {
      this.$confirm("是否导出?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let link = document.createElement("a");
          if (this.date.length > 0) {
            this.search.start_time = this.date[0];
            this.search.end_time = this.date[1];
          }
          if (this.dates.length > 0) {
            this.search.create_start = this.dates[0];
            this.search.create_end = this.dates[1];
          }
          if (this.dateTime.length > 0) {
            this.search.pay_start_date = this.dateTime[0];
            this.search.pay_end_date = this.dateTime[1];
          }
          if (this.tdDate.length > 0) {
            this.search.td_start_date = this.tdDate[0];
            this.search.td_end_date = this.tdDate[1];
          }
          let amountMsg = this.search.amount ? 1 : "";
          let statusType = this.search.status == 0 ? "" : this.search.status;
          let must_pay = this.search.must_pay == -1 ? "" : this.search.must_pay;
          link.href =
            this.$axios.defaults.baseURL +
            "/smkapi/statement/exportPaymentList?token=" +
            getToken() +
            "&bank=" +
            this.search.bank +
            "&bank_acount=" +
            this.search.bank_acount +
            "&start_date=" +
            this.search.start_time +
            "&end_date=" +
            this.search.end_time +
            "&td_start_date=" +
            this.search.td_start_date +
            "&td_end_date=" +
            this.search.td_end_date +
            "&sup_id=" +
            this.supplierNameList.id +
            "&category_code=" +
            this.classNameList.code +
            "&supplier_id=" +
            this.supplierNameList.code +
            "&status=" +
            statusType +
            "&must_pay=" +
            must_pay +
            "&serial_code=" +
            this.search.serial_code +
            "&amount=" +
            amountMsg +
            "&create_start=" +
            this.search.create_start +
            "&create_end=" +
            this.search.create_end +
            "&pay_start_date=" +
            this.search.pay_start_date +
            "&pay_end_date=" +
            this.search.pay_end_date +
            "&orgarea_code_str=" +
            this.search.area;
          link.click();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消导出"
          });
        });
    },
    // 搜索
    handleSearch() {
      if (this.date.length > 0) {
        this.search.start_time = this.date[0];
        this.search.end_time = this.date[1];
      }
      if (this.dates.length > 0) {
        this.search.create_start = this.dates[0];
        this.search.create_end = this.dates[1];
      }
      if (this.dateTime.length > 0) {
        this.search.pay_start_date = this.dateTime[0];
        this.search.pay_end_date = this.dateTime[1];
      }
      if (this.tdDate.length > 0) {
        this.search.td_start_date = this.tdDate[0];
        this.search.td_end_date = this.tdDate[1];
      }
      this.listData = [];
      this.pageData.page = 1;
      this.pageData.total = null;
      this.$refs.multipleTable.clearSelection();
      this.getData();
    },

    //修改付款银行账号
    sduitpayinfo(scope) {
      this.eduitestablishDialog.id = scope.row.id;
      this.eduitestablishDialog.paymentname = scope.row.payment_id;
      this.eduitestablishDialog.dialogType = "smksend";
      this.eduitestablishDialog.eduitDialogVisible = true;
    },
    //修改付款银行账号(多选)
    sduitpayallinfo() {
      if (this.selectedData.length <= 0) {
        this.$message({
          type: "error",
          message: "请勾选要修改付款银行账号的列表"
        });
        return;
      }
      this.eduitestablishDialog.id = this.selectedData.join(",");
      this.eduitestablishDialog.paymentname = "";
      // this.eduitestablishDialog.paymentname = this.selectedpaymengData.join(",");
      this.eduitestablishDialog.dialogType = "smksend";
      this.eduitestablishDialog.eduitDialogVisible = true;
    },
    //清空
    empty() {
      this.date = [];
      this.dates = [];
      this.dateTime = [];
      this.tdDate = [];
      // this.date.push(this.normal_startime);
      // this.date.push(this.normal_endtime);
      // this.dates.push(this.normal_startime);
      // this.dates.push(this.normal_endtime);
      this.classNameList.name = "";
      this.classNameList.code = "";
      this.search = {
        start_time: "",
        end_time: "",
        create_start: "",
        create_end: "",
        pay_start_date: "",
        pay_end_date: "",
        bank: "",
        bank_acount: "",
        serial_code: "",
        status: "",
        area: "",
        amount: false,
        pay_status: "",
        must_pay: "",
        td_start_date: "",
        td_end_date: ""
      };
      this.insideArea = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      };
      this.getAreaData();
      this.supplierNameList = {
        name: "",
        code: "",
        id: ""
      };
    },

    //每页多少条
    handleCurrentChange(val) {
      this.pageData.page = 1;
      this.pageData.pageSize = val;
      this.getData();
    },
    // 搜索供应商数据
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //选取页数
    handleSizeChange(page) {
      this.pageData.page = page;
      this.getData();
    },
    selectable(row, index) {
      if (row.status == 2 || row.states == "停用" || row.states == "冻结账款") {
        return false;
      } else {
        return true;
      }
    },
    //选取
    handleSelectionChange(val) {
      this.handleSelection = [];
      this.handleSelection = val;
      this.selectedData = [];
      this.listCenter = {};
      this.price = 0;
      val.forEach(res => {
        this.selectedData.push(res.id);
        this.price += parseFloat(res.settle);
        this.listData.forEach(result => {
          if (result[res.id]) {
            this.listCenter[res.id] = result[res.id];
          }
        });
      });
      this.price = this.price.toFixed(4);
    },
    area() {
      let arr = this.insideArea.options.filter(res => {
        return res.value == this.search.area;
      });
      this.center["区域"] = arr[0].label;
      console.log(this.center);
    },
    status() {
      let arr = this.option.filter(res => {
        return res.value == this.search.status;
      });
      this.center["付款单状态"] = arr[0].label;
    }
  },
  computed: {
    // checkedWeight() {
    //   let totalWeight = 0;
    //   this.selectedData.forEach(item => {
    //     totalWeight += item.weight;
    //   });
    //   return totalWeight.toFixed(2);
    // }
  }
};
</script>
<style scoped>
.top {
  position: relative;
  margin-bottom: 5px;
}

.price {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: 0;
  padding: 0 15px;
  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  width: 100px;
  margin-left: 5px;
}

.add {
  position: absolute;
  right: 0;
  top: 4px;
}

.pagination {
  text-align: right;
  padding: 10px;
}

.el-checkbox__inner {
  margin-top: 2px !important;
}
</style>
